package com.falcon.mvc.aop;

import com.swan.log.context.LogContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author zongf
 * @date 2024-02-04
 **/
@Slf4j
@Deprecated
//@Component
public class RequestIdInterceptor implements HandlerInterceptor {

    private ThreadLocal<Long> startHolder = new ThreadLocal<>();

    private static final String RESPONSE_LOG_ID = "LogId";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        startHolder.set(System.currentTimeMillis());
        LogContext.setLogId();

        log.info("请求开始, 请求类型: {}, 接口地址: {}", request.getMethod(), request.getRequestURI());

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

        // 响应头添加 LogId
        response.addHeader(RESPONSE_LOG_ID, LogContext.getLogId());

        // 计算耗时，如果
        Long start = startHolder.get();
        long cost = Objects.isNull(start) ? -1 : System.currentTimeMillis() - start;

        log.info("请求结束, 请求类型: {}, 接口地址: {}， 请求耗时: {}ms", request.getMethod(), request.getRequestURI(), cost);

        // 清除请求id
        LogContext.cleanLodId();
        startHolder.remove();
    }


}
